/*
 * File Name:               XLogHandler.cs
 * 
 * Description:             普通类
 * Author:                  yuhaoyu <158521902@qq.com>
 * Create Date:             2016/12/02
 */

using System;
using System.IO;
using UnityEngine;

public class XLogHandler : ILogHandler
{
    public static void start()
    {
        Debug.logger.logHandler = new XLogHandler(Debug.logger.logHandler);

        if (Write2File)
        {
            var dir = new DirectoryInfo(LogFilePath);
            if (!dir.Exists) dir.Create();
            LogFileName = LogFilePath + DateTime.Now.ToString("yyyy_MM_dd_HH_mm") + ".log";
            Application.logMessageReceivedThreaded += LogCallback;
        }
    }

    private ILogHandler mOldHandler;

    private static string DateFormat = "HH:mm:ss:fff";
    public static bool Write2Console = false;

    public static bool Write2File = false;
    public static string LogFilePath = Application.dataPath + "/../Logs/";
    private static string LogFileName;
    public static string FileFormat_Error = "[{0}][{1}][{2}]\n{3}\n";
    public static string FileFormat_Log = "[{0}][{1}][{2}]\n";
    private XLogHandler(ILogHandler oldHandler)
    {
        mOldHandler = oldHandler;
    }

    public void LogException(Exception exception, UnityEngine.Object context)
    {
        mOldHandler.LogException(exception, context);
    }

    public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args)
    {
        if (!Write2Console && !Write2File) return;

        var ret = string.Format("[{0}][{1}][{2}]", DateTime.Now.ToString(DateFormat), logType, format);
        ret = string.Format(ret, args);

        if (Write2Console)
            mOldHandler.LogFormat(logType, context, "{0}", ret);

        if (!Write2Console && Write2File)
            File.AppendAllText(LogFileName, ret + "\n");
    }

    private static void LogCallback(string condition, string stackTrace, LogType type)
    {
        string format = (type == LogType.Error || type == LogType.Exception) ? FileFormat_Error : FileFormat_Log;
        var ret = string.Format(format, DateTime.Now.ToString(DateFormat), type, condition, stackTrace);

        if (Write2File)
            File.AppendAllText(LogFileName, ret);
    }

    public static void setDateFormat(string format)
    {
        if (!Write2Console && !Write2File) return;

        DateFormat = format;
    }

    public static void setDateFormat<T>(string format, T arg0)
    {
        if (!Write2Console && !Write2File) return;

        DateFormat = string.Format(format, arg0);
    }
}
